import { ComponentClass } from 'react'
import Taro, { Component, Config } from '@tarojs/taro'
import { View, Input,Text,Button } from '@tarojs/components'
import { AtIcon, AtButton, AtToast } from 'taro-ui'
import CTitle from '../../components/CTitle'
 
// import {}  from "../../utils/encrypt/demo"
import { injectPlaySong } from '../../utils/decorators'
import { connect } from '@tarojs/redux'
import { baseUrl,baseUrlUg } from '../../config'
import api from '../../services/api'
// let CryptoJS = require("crypto");
import './index.scss'
// import CryptoJS from 'crypto-js/crypto-js'
// let crypto = require('crypto-js')
// import {login} from '../../actions/login'
type PageDispatchProps = {
   login: (cellphone, passwd) => any
}
type PageState = {
    phone: string,
    password: string,
    showLoading: boolean,
    showTip: boolean,
    tip: string
}

type InputType = 'phone' | 'password'

@injectPlaySong()
 @connect(( )=>{
    //  login(x,x)
 })
class Login extends Component<PageDispatchProps, PageState> {

  /**
   * 指定config的类型声明为: Taro.Config
   *
   * 由于 typescript 对于 object 类型推导只能推出 Key 的基本类型
   * 对于像 navigationBarTextStyle: 'black' 这样的推导出的类型是 string
   * 提示和声明 navigationBarTextStyle: 'black' | 'white' 类型冲突, 需要显示声明类型
   */
  config: Config = {
    navigationBarTitleText: '登录'
  }

  constructor (props) {
    super(props)
    this.state = {
        phone: '',
        password: '',
        showLoading: false,
        showTip: false,
        tip: ''
    }
  }
  // startDecry=(encryptedData, iv,sessKey,appId)=>{
  //     // return this.decryptData(encryptedData, iv,sessKey,appId)
  //     // 解密后的数据为
  //     //
  //     // data = {
  //     //   "nickName": "Band",
  //     //   "gender": 1,
  //     //   "language": "zh_CN",
  //     //   "city": "Guangzhou",
  //     //   "province": "Guangdong",
  //     //   "country": "CN",
  //     //   "avatarUrl": "http://wx.qlogo.cn/mmopen/vi_32/aSKcBBPpibyKNicHNTMM0qJVh8Kjgiak2AHWr8MHM4WgMEm7GFhsf8OYrySdbvAMvTsw3mo8ibKicsnfN5pRjl1p8HQ/0",
  //     //   "unionId": "ocMvos6NjeKLIBqg5Mr9QjxrP1FA",
  //     //   "watermark": {
  //     //     "timestamp": 1477314187,
  //     //     "appid": "wx4f4bc4dec97d474b"
  //     //   }
  //     // }
  // }
  // decryptData=(encryptedData, iv,sessKey,appId)=>{
  //     // base64 decode
  //     var sessionKey = new Buffer(sessKey, 'base64')
  //     encryptedData = new Buffer(encryptedData, 'base64')
  //     iv = new Buffer(iv, 'base64')

  //     try {
  //       // 解密
  //       var decipher = crypto.createDecipheriv('aes-128-cbc', sessionKey, iv)
  //       // 设置自动 padding 为 true，删除填充补位
  //       decipher.setAutoPadding(true)
  //       var decoded = decipher.update(encryptedData, 'binary', 'utf8')
  //       decoded += decipher.final('utf8')
        
  //       decoded = JSON.parse(decoded)

  //     } catch (err) {
  //       throw new Error('Illegal Buffer')
  //     }

  //     if (decoded.watermark.appid !==  appId) {
  //       throw new Error('Illegal Buffer')
  //     }

  //     return decoded
  // }
  openSettingToAuthorize() {
    Taro.showModal({
      title: '提示',
      confirmText: '去授权',
      content: '您没有权限，是否去授权?',
      success: ({ confirm }) => {
        if (confirm) {
          Taro.openSetting({})
        } else {
          Taro.showToast({
            title: '保存失败，请重试',
            icon: 'none',
            duration: 2000,
          })
        }
      }
    })
  }
  componentWillMount(){
    if(  Taro.getStorageSync('openid') &&  Taro.getStorageSync('session_key') ){
      Taro.reLaunch({
        url: '/pages/index/index'
      })
    } else {
      this.autoLogin()
    }
    
  }
  //获取sesskey
  getSessKey = () =>{
    Taro.checkSession({
      success: function(e) {
         
        console.log("session_key 未过期"+JSON.stringify(e))
        //session_key 未过期，并且在本生命周期一直有效
      },
      fail: function() {
        // session_key 已经失效，需要重新执行登录流程
        // 登录
        
      }
    })
  }
  componentDidMount(){
  //   Taro.getUserInfo(params).then((res)=>{
  //     console.log("用户信息："+JSON.stringify(res))
  // }) 
  }
  componentWillReceiveProps (nextProps) {
    console.log(this.props, nextProps)
  }

  componentWillUnmount () { }

  componentDidShow () {
   }

  componentDidHide () { }
   

  handleChange (type: InputType, event) {
    const { value } = event.detail
    if (type === 'phone') {
        this.setState({
            phone: value
        })
    } else {
        this.setState({
            password: value
        })
    }
  }
  getUserInfo=(userInfo)=>{
    console.log('userinfo',userInfo)
    if(userInfo.detail.userInfo){   //同意
        // this.props.setBasicInfo(userInfo.detail.userInfo) //将用户信息存入redux
        Taro.setStorage({key:'userInfo',data:userInfo.detail.userInfo}).then(rst => {  //将用户信息存入缓存中
            // Taro.navigateBack()
            //  this.loginug( ) 
            
        })
    }  
  }
  autoLogin=()=>{
    Taro.login({

      success: function (r) {
         
        var code = r.code;//登录凭证
        if (code) {
           //2、调用获取用户信息接口
           Taro.getUserInfo({
              success: function (res) {
                console.log({encryptedData: res.encryptedData, iv: res.iv, code: code})
                Taro.request({
                  url: baseUrlUg+'?decodeUserInfo',//自己的服务接口地址
                  method: 'POST',
                  header: {
                    'content-type': 'application/x-www-form-urlencoded'
                  },
                  data: {encryptedData: res.encryptedData, iv: res.iv, code: code},
                  success:function(data){
                    //4.解密成功后 获取自己服务器返回的结果
                      
                     console.log("openid:"+data.data.openId)
                     console.log("session_key:"+data.data.session_key)
                     Taro.setStorageSync('openid',  data.data.openId)
                     Taro.setStorageSync('session_key',  data.data.session_key)
                     if(data.data.openId && data.data.session_key){
                         
                         Taro.showToast({
                          title:'登陆成功',
                          icon:'success',
                          duration:2000
                        })
                        Taro.reLaunch({
                          url: '/pages/index/index'
                        })
                     } else {
                      Taro.showToast({
                        title:'登陆失败',
                        icon:'fail',
                        duration:2000
                      })
                     }
                    // if (data.data.status == 1) {
                    //     var userInfo_ = data.data.userInfo;
                    //     console.log(userInfo_)
                    // } else {
                    //     console.log('解密失败')
                    // }
                  },
                  fail: function () {
                    console.log('系统错误,解密失败')
                    Taro.showToast({
                      title:'登陆失败,网络中断',
                      icon:'none',
                      duration:2000
                    })
                  }
                })
              
              }
           })
        }
      },
      fail: function(res){
        Taro.showToast({
          title:'网络中断' ,
          icon:'fail',
          duration:3500
        })
      }
    })
  }
  loginByTaros(){
     this.getSessKey()
  // let appid="wxae6c4206ce99a36f"
    Taro.login({
      success: function(res) {
       
        if(res.code){
           
           console.log(res);
           Taro.request({
              // url: this.globalData.path + '/miniLogin/login.ajax',
              url:"https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code",
              data: {
                code: res.code
              },
              success: res => {
                 
                 let mylogininfo = res.data.data
                 if (mylogininfo != null) {
                   
                  console.log(mylogininfo)
                 }
              }
           })
           //avater
        }
      }
    } )
  }
  getPhoneNumber=(data)=>{
    console.log('PhoneNumber:',data)
   
  }
  render () {
    const { showLoading, tip, showTip } = this.state
    return (
      <View className='login_container'>
        <CTitle isFixed={false} />
        <View className='login_content'>
        <View>
               
              <Button open-type='getUserInfo' onGetUserInfo={ this.autoLogin}>  点击微信授权登陆</Button>

          </View> 
           
           
          {/* <View>
              <Text>申请获取你的公开信息（测试后端登陆接口）</Text> 
              <Button open-type='getUserInfo' onGetUserInfo={this.getUserInfo} > 微信授权登陆 </Button>
          </View>  */}
            {/* <View className='login_content__item'>
                <AtIcon value='iphone' size='24' color='#ccc'></AtIcon>
                <Input type='text' placeholder='手机号' className='login_content__input'
                    style={{minWidth:'100%'}}
                 onInput={ (e) : void => {this.handleChange('phone', e)} } />
            </View>
            <View className='login_content__item'>
                <AtIcon value='lock' size='24' color='#ccc'></AtIcon>
                <Input type='text' password placeholder='密码' className='login_content__input'
                  style={{minWidth:'100%'}}
                onInput={ (e) : void => {this.handleChange('password', e)} } />
            </View>
            <AtButton className='login_content__btn' onClick={this.login.bind(this)}>登录</AtButton> */}
        </View>
        <AtToast isOpened={showLoading} text='登录中' status='loading' hasMask duration={30000000}></AtToast>
        <AtToast isOpened={showTip} text={tip} hasMask duration={2000}></AtToast>
      </View>
    )
  }
}

export default Login as ComponentClass
